package common

import (
	"fmt"
	"gorm.io/driver/postgres"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"os"
)

func NewPostgres(dsn string) (db *gorm.DB, err error) {
	if dsn == "" {
		// 从环境变量构建 DSN
		dsn = fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=disable",
			os.Getenv("PG_HOST"),
			os.Getenv("PG_PORT"),
			os.Getenv("PG_USER"),
			os.Getenv("PG_PASSWORD"),
			os.Getenv("PG_DBNAME"),
		)
	}
	return gorm.Open(postgres.Open(dsn), &gorm.Config{Logger: logger.Default})
}
